package com.wellview.template.view;


import android.annotation.TargetApi;
import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.os.Bundle;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.bigkoo.convenientbanner.ConvenientBanner;
import com.bigkoo.convenientbanner.holder.CBViewHolderCreator;
import com.bigkoo.convenientbanner.holder.Holder;
import com.bumptech.glide.Glide;
import com.tencent.smtt.export.external.extension.interfaces.IX5WebSettingsExtension;
import com.tencent.smtt.export.external.extension.interfaces.IX5WebViewExtension;
import com.tencent.smtt.export.external.interfaces.IX5WebChromeClient;
import com.tencent.smtt.export.external.interfaces.JsResult;
import com.tencent.smtt.export.external.interfaces.WebResourceRequest;
import com.tencent.smtt.export.external.interfaces.WebResourceResponse;
import com.tencent.smtt.sdk.ValueCallback;
import com.tencent.smtt.sdk.WebChromeClient;
import com.tencent.smtt.sdk.WebSettings;
import com.tencent.smtt.sdk.WebView;
import com.tencent.smtt.sdk.WebViewClient;
import com.wellview.template.App;
import com.wellview.template.BaseActivity;
import com.wellview.template.Constant;
import com.wellview.template.R;
import com.wellview.template.bean.StartBean;
import com.wellview.template.logger.Logger;
import com.wellview.template.modle.BehaviorFactory;
import com.wellview.template.modle.JSBehavior;
import com.wellview.template.modle.SplashBehavior;
import com.wellview.template.share.AuthJavaScriptAccept;
import com.wellview.template.sonic.SonicConfig;
import com.wellview.template.sonic.SonicConstants;
import com.wellview.template.sonic.SonicEngine;
import com.wellview.template.sonic.SonicRuntimeImpl;
import com.wellview.template.sonic.SonicSession;
import com.wellview.template.sonic.SonicSessionClientImpl;
import com.wellview.template.sonic.SonicSessionConfig;
import com.wellview.template.utils.EventCenter;
import com.wellview.template.utils.MediaUtility;
import com.wellview.template.utils.NetBroadcastReceiver;
import com.wellview.template.utils.NetTools;
import com.wellview.template.utils.ScreenUtil;
import com.wellview.template.utils.SharePrefrenceUtil;
import com.wellview.template.utils.StatusBarUtils;
import com.wellview.template.utils.Utils;
import com.wellview.template.utils.XulUtils;
import com.wellview.template.widget.DoubleBallProgress;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;



public class MainActivity extends BaseActivity implements SplashBehavior.OnStartResponse {


    public static final String LOCAL_ERROR_PAGE = "file:///android_asset/neterror.html";
    public static final int COUNT_DOWN = 12;

    private boolean isRefresh = false;
    @BindView(R.id.web_content)
    WebView webContent;
//    @BindView(R.id.srl_layout)
//    SmartRefreshLayout smartRefreshLayout;

    @BindView(R.id.pb_progress)
    ProgressBar pbProgress;

    @BindView(R.id.tv_version)
    TextView tvVersion;

    @BindView(R.id.db_progress)
    DoubleBallProgress dbProcess;


    @BindView(R.id.btn_test)
    Button btnTest;
    @BindView(R.id.rtl_webContent)
    RelativeLayout rtlWebContent;





    public static final int AUTO_TURNING_TIME = 2000;
    @BindView(R.id.banner_layout)
    RelativeLayout bannerLayout;
    @BindView(R.id.cb_welcome)
    ConvenientBanner cbWelcome;
    @BindView(R.id.tv_count)
    TextView tvCount;

    private boolean hasGO = false;



    private ValueCallback<Uri> uploadFile;
    private ValueCallback<Uri[]> uploadFiles;

    private String FUNCTION_HEAD = "dzwb://";
    public static final String FUNCTION_CALL = "tel:";
    private JSBehavior jsBehavior;

    private NetBroadcastReceiver broadcastReceiver;
    private String postBody;
    private int counter = 0;

    private boolean isNetPrepare = false;

    private NetTools.NetState curState = NetTools.NetState.NONE;


    /**
     * 当前主页面的地址
     */
    private String curHomeAdderss;
    /**
     * 访问发生错误的页面
     */
    private String toErrorPage;
    private SonicSession sonicSession;
    private SonicSessionClientImpl sonicSessionClient;
    private boolean isFirst = true;
    private AuthJavaScriptAccept authJavaScriptAccept;
    //处理banner图
    private SplashBehavior splashBehavior;
    private boolean isShowBanner;
    //是否是用sonic
    private boolean useSonic = false;
    private boolean isOutBrowse;


    @Override
    protected void beforeShow(Bundle savedInstanceState) {
//        getWindow().setFormat(PixelFormat.TRANSLUCENT);
        EventBus.getDefault().register(this);
        registerBrocast();
        Logger.i(TAG, "SHA1 >> " + Utils.sHA1(this));
        jsBehavior = new JSBehavior(this);
        splashBehavior = (SplashBehavior) BehaviorFactory.create(SplashBehavior.class);
        Intent intent = getIntent();
        String url = intent.getStringExtra("url");
        if (!TextUtils.isEmpty(url)){

        }else {
            splashBehavior.setStartListener(this);
        }

        if (useSonic){
            initSonic();
        }
    }

    private void initSonic() {
        if (!SonicEngine.isGetInstanceAllowed()) {
            SonicEngine.createInstance(new SonicRuntimeImpl(getApplication()), new SonicConfig.Builder().build());
        }
        SonicSessionConfig.Builder sessionConfigBuilder = new SonicSessionConfig.Builder();
        sessionConfigBuilder.setAcceptDiff(true);
        sessionConfigBuilder.setSessionMode( SonicConstants.SESSION_MODE_QUICK);
       sonicSession = SonicEngine.getInstance().createSession(Constant.URL_Main, sessionConfigBuilder.build());
        Logger.i(TAG,"sonicSession is null ? "+(sonicSession == null));
        if (null != sonicSession) {
            sonicSession.bindClient(sonicSessionClient = new SonicSessionClientImpl());
        } else {
            // this only happen when a same sonic session is already running,
            // u can comment following codes to feedback as a default mode.
            // throw new UnknownError("create session fail!");
//            Toast.makeText(this, "create sonic session fail!", Toast.LENGTH_LONG).show();
        }
    }

    @Override
    public void bindView() {
        setContentView(R.layout.activity_main);
    }

    @Override
    public void findAllViews() {
//        tvVersion.setText("\nversion "+ QbSdk.getTbsVersion(this));
    }

    @Override
    public void setAllListeners() {
//        smartRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
//            @Override
//            public void onRefresh(RefreshLayout refreshlayout) {
//                isRefresh = true;
//                if (webContent != null) {
//                    if (isErrorPage(webContent.getUrl())){
//                        if (webContent.canGoBack()){
//                            webContent.goBack();
//                        }else {
//                            Logger.i(TAG, "to error page is " + toErrorPage);
//                            webContent.loadUrl(toErrorPage);
//                        }
//                    }else {
//                        //if net is connect
//                        webContent.reload();
//                    }
//                    Logger.i(TAG, "onRefresh cur refresh url is " + webContent.getUrl());
//                }
//            }
//        });

        btnTest.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
//                jsBehavior.handleFunction("action_share");
//                authJavaScriptAccept.actionSelectUserAvanter("");

            }
        });
    }


    public long time = 0;
    @Override
    public void doProcess() {
        Logger.i(TAG,"time : 2"+ XulUtils.timestamp());
        Intent intent = getIntent();
        String actionLoadUrl = intent.getStringExtra("url");
        if (TextUtils.isEmpty(actionLoadUrl)){
            showBannerProcess();
        }
        initWebcontent();
        webContent.setWebChromeClient(new WebChromeClient() {
            @Override
            public void onProgressChanged(WebView view, int newProgress) {
                Logger.i(TAG, "onProgressChanged >> " + newProgress + "isRefresh >> " + isRefresh);
//                && !smartRefreshLayout.isRefreshing()
//                if (pbProgress != null ){
//                    if (pbProgress.getVisibility() != View.VISIBLE){
//                        pbProgress.setVisibility(View.VISIBLE);
//                    }
//                    pbProgress.setProgress(newProgress);
//                }
//                if (newProgress == 100) {
//                    if (isRefresh) {
//                        isRefresh = false;
////                        smartRefreshLayout.finishRefresh(true);
//                    }
//                    pbProgress.setVisibility(View.GONE);
//                }
                if (dbProcess != null ){
                    if (isRefresh){
                        if (dbProcess.getVisibility() != View.VISIBLE){
                            dbProcess.setVisibility(View.VISIBLE);
                        }
                    }
                }
                if (newProgress == 100) {
                    if (isRefresh) {
                        isRefresh = false;
//                        smartRefreshLayout.finishRefresh(true);
                    }
                    dbProcess.setVisibility(View.GONE);
                }
                super.onProgressChanged(view, newProgress);
            }

            // For Android 3.0+
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
                Log.i("test", "openFileChooser 1");
                MainActivity.this.uploadFile = uploadMsg;
                openFileChooseProcess();
            }

            // For Android < 3.0
            public void openFileChooser(ValueCallback<Uri> uploadMsgs) {
                Log.i("test", "openFileChooser 2");
                MainActivity.this.uploadFile = uploadMsgs;
                openFileChooseProcess();
            }

            // For Android  > 4.1.1
            public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
                Log.i("test", "openFileChooser 3");
                MainActivity.this.uploadFile = uploadMsg;
                openFileChooseProcess();
            }

            // For Android  >= 5.0
            public boolean onShowFileChooser(com.tencent.smtt.sdk.WebView webView,
                                             ValueCallback<Uri[]> filePathCallback,
                                             WebChromeClient.FileChooserParams fileChooserParams) {
                Log.i("test", "openFileChooser 4:" + filePathCallback.toString());
                MainActivity.this.uploadFiles = filePathCallback;
                openFileChooseProcess();
                return true;
            }
            @Override
            public boolean onJsAlert(WebView webView, String s, String s1, JsResult jsResult) {
                return super.onJsAlert(webView, s, s1, jsResult);
            }

            @Override
            public void onShowCustomView(View view, IX5WebChromeClient.CustomViewCallback customViewCallback) {
                super.onShowCustomView(view, customViewCallback);
                Logger.i(TAG,"view "+view+customViewCallback);
            }

            @Override
            public void onShowCustomView(View view, int i, IX5WebChromeClient.CustomViewCallback customViewCallback) {
                super.onShowCustomView(view, i, customViewCallback);
                Logger.i(TAG,"view "+view+customViewCallback);
            }

            @Override
            public void onHideCustomView() {
                Logger.i(TAG,"onHideCustomView ");
                super.onHideCustomView();
            }

            @Override
            public Bitmap getDefaultVideoPoster() {
                Logger.i(TAG,"getDefaultVideoPoster ");
                return BitmapFactory.decodeResource(getResources(),R.drawable.app);
            }



            @Override
            public View getVideoLoadingProgressView() {
                return super.getVideoLoadingProgressView();
            }
        });
        WebViewClient webViewClient = new WebViewClient() {
            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                if (isFirst) {
                    StatusBarUtils.setWindowStatusBarColor(MainActivity.this, Color.parseColor("#3a8fb7"));
                    isFirst = false;
                }
                Logger.i(TAG, "onPageStarted start url is >> " + url);
                if (!isAllowRefreshPage(url)) {
//                    smartRefreshLayout.setEnableRefresh(false);
                } else {
//                    smartRefreshLayout.setEnableRefresh(false);
                }
                super.onPageStarted(view, url, favicon);
                time = System.currentTimeMillis();
                Log.i(TAG, "onPageStarted : " + time + "is X5" + App.isX5Core());
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                Log.i(TAG, "onPageStarted : use time ms " + (System.currentTimeMillis() - time));
                Logger.i(TAG, "onPageFinished finish url is >>" + url);
                Logger.i(TAG, "onPageFinished : getUrl " + view.getUrl());
                if (useSonic){
                    if (sonicSession != null) {
                        sonicSession.getSessionClient().pageFinish(url);
                    }
                }
            }

            @Override
            public void onReceivedError(WebView webView, int i, String s, String s1) {
//                Logger.e(TAG, "onReceivedError >> " + error.getErrorCode() + error.getDescription());
//                Logger.e(TAG, "onReceivedError uri " + request.getUrl());
//                setErrorRecode(request.getUrl());
                super.onReceivedError(webView, i, s, s1);
            }

            @Override
            public void onReceivedHttpError(WebView webView, WebResourceRequest webResourceRequest, WebResourceResponse webResourceResponse) {
                Logger.i(TAG, "onReceivedHttpError>>" + webResourceResponse.getStatusCode());
                super.onReceivedHttpError(webView, webResourceRequest, webResourceResponse);
            }

            @TargetApi(21)
            @Override
            public WebResourceResponse shouldInterceptRequest(final WebView view, WebResourceRequest request) {
//                Logger.i(TAG, "shouldInterceptRequest>>");
                Logger.i(TAG,"Thread :>>"+Thread.currentThread().getName());

                return super.shouldInterceptRequest(view, request);
            }

            @Override
            public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
                if (useSonic){
                    if (sonicSession != null) {
                        return (WebResourceResponse) sonicSession.getSessionClient().requestResource(url);
                    }
                }
                return super.shouldInterceptRequest(view,url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                Logger.i(TAG, "url is>>" + url + ">> url.startsWith(FUNCTION_HEAD) " + url.startsWith(FUNCTION_HEAD));
                if (!TextUtils.isEmpty(url) && url.startsWith(FUNCTION_HEAD)) {
                    String substring = url.substring(FUNCTION_HEAD.length(), url.length());
                    Logger.i(TAG, "substring is >> " + substring);
                    jsBehavior.handleFunction(substring);
                    return true;
                }
                if (!TextUtils.isEmpty(url) && url.contains(FUNCTION_CALL)) {
                    jsBehavior.handleFunction(url);
                    return true;
                }
                return super.shouldOverrideUrlLoading(view, url);
            }


        };
        webContent.setWebViewClient(webViewClient);
        ///////////////////ShareSDK///////////////////
//        ShareSDKUtils.prepare(webContent,webViewClient);
        authJavaScriptAccept = new AuthJavaScriptAccept(this,jsBehavior);
        webContent.addJavascriptInterface(authJavaScriptAccept,"Android");
        ///////////////////ShareSDK//////////////////

        //检测升级
//        jsBehavior.handleFunction(JSBehavior.ACTION_CHECKUPDATE);

        if (!TextUtils.isEmpty(actionLoadUrl)){
            tvCount.setVisibility(View.GONE);
            loadPage(actionLoadUrl);
            isOutBrowse = true;
        }
    }

    private void openFileChooseProcess() {
        Intent i = new Intent(Intent.ACTION_GET_CONTENT);
        i.addCategory(Intent.CATEGORY_OPENABLE);
        i.setType("image/*");
        startActivityForResult(Intent.createChooser(i, "test"), 0);
    }


    private void setErrorRecode(Uri url) {
        toErrorPage = url.toString();
    }

    private void initWebcontent() {
        WebSettings settings = webContent.getSettings();
        settings.setDisplayZoomControls(false);
        settings.setJavaScriptEnabled(true);
        settings.setSupportZoom(false);// 不支持缩放
//        settings.setUseWideViewPort(false);// 将图片调整到适合webview大小
//        settings.setLoadWithOverviewMode(false);// 缩放至屏幕的大小
        initWebContentCacheBaseOnNetwork(NetTools.isConnected());
//        settings.setLoadWithOverviewMode(true);
        settings.setBuiltInZoomControls(false);

        settings.setDatabaseEnabled(true);
        settings.setDomStorageEnabled(true);
        settings.setAppCacheEnabled(true);
        settings.setAppCacheMaxSize(15 * 1024 * 1024);
        settings.setAppCachePath(this.getFilesDir() + File.separator + "web_cache");
        settings.setAllowFileAccess(true);
        settings.setTextSize(WebSettings.TextSize.NORMAL);
        settings.setUseWideViewPort(true);
        settings.setLoadWithOverviewMode(true);
        settings.setRenderPriority(WebSettings.RenderPriority.HIGH);

        webContent.setVerticalScrollbarOverlay(false);
        webContent.setVerticalScrollBarEnabled(false);
        webContent.setHorizontalScrollBarEnabled(false);

        IX5WebSettingsExtension x5Setting = webContent.getSettingsExtension();
        if (x5Setting != null) {
            x5Setting.setPreFectch(true);
//            x5Setting.setRecordRequestEnabled(true);
        }
        IX5WebViewExtension x5WebSetting = webContent.getX5WebViewExtension();
        if (x5WebSetting != null) {
            x5WebSetting.setScrollBarFadingEnabled(false);
            x5WebSetting.setVerticalScrollBarEnabled(false);
            Bundle data = new Bundle();
//            data.putBoolean("standardFullScreen", true);
//            //true表示标准全屏，false表示X5全屏；不设置默认false，
            data.putBoolean("supportLiteWnd", false);
            //false：关闭小窗；true：开启小窗；不设置默认true，
            data.putInt("DefaultVideoScreen", 1);
            //1：以页面内开始播放，2：以全屏开始播放；不设置默认：1
            webContent.getX5WebViewExtension().invokeMiscMethod("setVideoParams", data);
        }
    }

    public void initWebContentCacheBaseOnNetwork(boolean isConnected){
        WebSettings settings = webContent.getSettings();
        Logger.i(TAG, "initWebContentCacheBaseOnNetwork is connected " + isConnected);
        if (isConnected) {
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);//有网络连接
        } else {
            settings.setCacheMode(WebSettings.LOAD_NO_CACHE);//无网络连接
        }
    }

    @Override
    protected void handleChildMsg(Message msg) {
        super.handleChildMsg(msg);
        switch (msg.what) {
            case COUNT_DOWN:
                setCount();
                break;
            default:
                break;
        }
        stopProgressDialog();
    }

    private void setCount() {
        if (hasGO){
            return;
        }
        Logger.i(TAG, " count is " + count);
        if (count > 0) {
            count--;
//                   tvCount.setText("跳过");
        } else {
            Logger.i(TAG, " count is " + count);
        }
        if (count <= 0) {
            decideToGo();
            count = 3;
        }
        getHandler().sendEmptyMessageDelayed(COUNT_DOWN,1800);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleNetWorkMessage(Object msg) {
        Logger.i(TAG, "<< handle start PageA or start PageB >> time " + System.currentTimeMillis());
        EventCenter eventCenter = (EventCenter) msg;
        int resultCode = eventCenter.getResultCode();
        if (resultCode != Constant.MESSAGE_NETWORK) {
            return;
        }

        Object[] netMsg = (Object[]) eventCenter.getMsg();
        NetTools.NetState netState = (NetTools.NetState) netMsg[0];
        boolean isAviliable = (boolean) netMsg[1];
        Logger.i(TAG, "handleNetWorkMessage >> " + netState.toString());
        if (netState == NetTools.NetState.WIFI) {
            curState = netState;
        }
        if (netState == NetTools.NetState.MOBILE) {
            curState = netState;
        }
        if (!isAviliable) {
            Logger.i(TAG, "cur net is not aviliable please check");
            Toast.makeText(this, "当前网络不可用", Toast.LENGTH_SHORT).show();
        } else {

        }

        initWebContentCacheBaseOnNetwork(isAviliable);
    }

    public String getCurHomeAddress() {
        Logger.i(TAG, "curHomeAdderss is >> " + curHomeAdderss);
        return curHomeAdderss;
    }


    public void loadPage(String url) {
        Logger.i(TAG, "loadPage url is " + url);
        if (useSonic && sonicSessionClient != null ) {
            Logger.i(TAG,"loadPage with sonicSessionClient ");
            sonicSessionClient.bindWebView(webContent);
            sonicSessionClient.clientReady();
        } else { // default mode
            webContent.loadUrl(url);
        }
    }

    private void registerBrocast() {
        broadcastReceiver = new NetBroadcastReceiver();
        IntentFilter filter = new IntentFilter();
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
        registerReceiver(broadcastReceiver, filter);
    }

    private void unRegisterBrocast(){
        if(broadcastReceiver!=null){
            unregisterReceiver(broadcastReceiver);
        }
    }

    private long lastFinishTime ;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        Logger.i(TAG, "onKeyDown ==>> " + keyCode);
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            boolean canGoBack = webContent.canGoBack();
            String goUrl = webContent.getUrl();
            String originalUrl = webContent.getOriginalUrl();
            Logger.i(TAG, "canGoBack canGoBack >> " + canGoBack
                    + "\n:>> go back url is " + goUrl
                    + "\n>> originalUrl :  " + originalUrl
                    + "\ntime>>" + System.currentTimeMillis());
//            if (isOutBrowse ){
//
//            }
            if (!canGoBack ){
                if (!originalUrl.equals(Constant.URL_Main) && isOutBrowse){
                    webContent.clearHistory();
                    loadPage(Constant.URL_Main);
                    isOutBrowse = false;
                    return true;
                }
                return doubleClick();
            }
            if (canGoBack) {
//                if (isNeedExitUrl(goUrl)){
//                    return doubleClick();
//                }
                webContent.goBack();
                return true;
            }
//            if (canGoBack && LOCAL_ERROR_PAGE.equals(originalUrl)){
//                return doubleClick();
//            }
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }



    /**
     * 双击是否退出
     * @return
     */
    private boolean doubleClick() {
        Logger.i(TAG, " need to finish System.currentTimeMillis() " + System.currentTimeMillis() + " >> lastFinishTime " + lastFinishTime);
        long currentTimeMillis = System.currentTimeMillis();
        if (currentTimeMillis - lastFinishTime < 2000) {
            finish();
        } else {
            showToast("再按一次退出");
            lastFinishTime = currentTimeMillis;
            return true;
        }
        lastFinishTime = currentTimeMillis;
        return false;
    }

    @Override
    protected void onDestroy() {
        Logger.i(TAG,"onDestroy onDestroy");
        unRegisterBrocast();
        try {
            if (useSonic && null != sonicSession) {
                sonicSession.destroy();
                sonicSession = null;
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (jsBehavior != null) {
            jsBehavior.destory();
        }
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @OnClick({R.id.tv_count})
    public void onViewClicked(View v) {
        switch (v.getId()){
            case R.id.tv_count:
                decideToGo();
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (jsBehavior != null){
            jsBehavior.onActivityResult(requestCode,resultCode,data);
        }
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case 0:
                    if (null != uploadFile) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();
                       Logger.i(TAG,"result >> "+result.toString());
                       if (TextUtils.isEmpty(result.toString())){
                           uploadFile.onReceiveValue(null);
                       }
                        String path = MediaUtility.getPath(getApplicationContext(),
                                result);
                        Logger.i(TAG,"path >> "+result.toString());
                        Uri uri = Uri.fromFile(new File(path));
                       uploadFile.onReceiveValue(uri);
                       uploadFile = null;
                    }
                    if (null != uploadFiles) {
                        Uri result = data == null || resultCode != RESULT_OK ? null
                                : data.getData();

                        if (TextUtils.isEmpty(result.toString())){
                            uploadFiles.onReceiveValue(null);
                        }
                        String path = MediaUtility.getPath(getApplicationContext(),
                                result);
                        Logger.i(TAG,"path >> "+result.toString());
                        Uri uri = Uri.fromFile(new File(path));
                        uploadFiles.onReceiveValue(new Uri[]{uri});
                        uploadFiles = null;
                    }
                    break;
                default:
                    break;
            }
        } else if (resultCode == RESULT_CANCELED) {
            if (null != uploadFile) {
                uploadFile.onReceiveValue(null);
                uploadFile = null;
            }

        }
    }

    public WebView getWebContent(){
        return webContent;
    }

    public boolean isNeedExitUrl(String url){
        if (    (Constant.URL_Main + "/live").equals(url)
                || (Constant.URL_Main + "/").equals(url)
                || (Constant.URL_Main + "/").equals(url)
                || url.startsWith(Constant.URL_Main + "/?_sonic_id")
                || (Constant.URL_Main + "/media").equals(url)
                || (Constant.URL_Main + "/news").equals(url)
//                || (Constant.URL_Main + "/info").equals()
//                || LOCAL_ERROR_PAGE.equals(url)
                || TextUtils.isEmpty(url)
                ) {
            return true;
        }
        return false;
    }

    public boolean isAllowRefreshPage(String url){
        if (!TextUtils.isEmpty(url) && url.startsWith(Constant.URL_Main + "/videoDatail.html?by=")){
            return false;
        }
        return true;
    }

    public boolean isErrorPage(String url){
        return LOCAL_ERROR_PAGE.equals(url);
    }

    private Dialog dialog;

    public void showGenralProgress(int progress, int total) {
        Logger.i(TAG,"showGenralProgress + progress"+progress+"total"+total);
        if (dialog == null) {
            dialog = new Dialog(this, R.style.CustomProgressDialog);
            dialog.setContentView(R.layout.dialog_update_avantar);
        }
        dialog.show();
        ProgressBar progressBar = dialog.findViewById(R.id.pb_progress);
        if (progressBar != null && progressBar.getMax() != total) {
            progressBar.setMax(total);
        }
        if (progressBar != null && dialog.isShowing()) {
            progressBar.setProgress(progress);
        }
        if (progress == total) {
            if (dialog != null && dialog.isShowing()) {
                dialog.dismiss();
            }
        }
    }

    public void  showBannerProcess(){
        Logger.i(TAG,"isFirstIn()"+isFirstIn());
        if (isFirstIn()) {
            checkPermissions(perms);
            tvCount.setText("立即体验");
        } else {
            tvCount.setText("跳过");
        }
        boolean networkConnected = NetTools.isNetworkConnected(this);
        Logger.i(TAG, "networkConnected >> " + networkConnected);
        Object o = Utils.readObject(App.getInstance(),"splash", "home.txt");
        Logger.i(TAG,"o is null "+(o == null));
        if (o != null) {
            try {
                List<StartBean> beans = ( List<StartBean>) o;
                showBanner(beans);
                Logger.i(TAG,"readObject OK ");
            }catch (Exception e){
                Logger.e(TAG,"readObject Exception ");
                showDefaultBanner();
            }
        }else {
            showDefaultBanner();
        }
        if (networkConnected) {
            splashBehavior.requestStartPage();
        }
    }

    @Override
    public void startResponseSuccess(List<StartBean> bean) {
        if (!isShowBanner){
            showBanner(bean);
        }
    }

    @Override
    public void startResponseFailed(Exception e) {
        if (!isShowBanner){
            showDefaultBanner();
        }
    }

    private void showBanner(final List<StartBean> beans) {
        isShowBanner = true;
        cbWelcome.setPages(new CBViewHolderCreator() {
            @Override
            public Object createHolder() {
                return new BannerHolder();
            }
        }, beans)
//                .setPageIndicator(new int[]{R.drawable.shape_coner_green, R.drawable.shape_coner_white})
//                .startTurning(AUTO_TURNING_TIME)
                .setCanLoop(false);
        if (!isFirstIn()){
            timerToGoMain();
        }
    }

    private int count = 3;

    private void timerToGoMain() {
        if (hasGO){
            return;
        }
        getHandler().sendEmptyMessageDelayed(COUNT_DOWN,1800);

    }

    private void showDefaultBanner() {
        isShowBanner = true;
        ArrayList<Integer> res = new ArrayList<>();
        if (ScreenUtil.getScreenHeight() * 1f/ ScreenUtil.getScreenWidth()  >= 1.9f){
            res.add(R.drawable.start21);
            res.add(R.drawable.start22);
            res.add(R.drawable.start23);
        }else {
            res.add(R.drawable.start1);
            res.add(R.drawable.start2);
            res.add(R.drawable.start3);
        }


        cbWelcome.setPages(new CBViewHolderCreator() {
            @Override
            public Object createHolder() {
                return new BannerDefaultHolder();
            }
        },res)
//                .setPageIndicator(new int[]{R.drawable.shape_coner_green,R.drawable.shape_coner_white})
//                .startTurning(AUTO_TURNING_TIME)
                .setCanLoop(false);
        if (!isFirstIn()){
            timerToGoMain();
        }
    }

    class BannerHolder implements Holder<StartBean> {

        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setLayoutParams(new LinearLayout.LayoutParams(ScreenUtil.getScreenWidth(context)
                    ,ScreenUtil.getScreenHeight(context)));
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, StartBean data) {
            Glide.with(context)
                    .load(data.getNetPath())
                    .override(ScreenUtil.getScreenWidth(context),ScreenUtil.getScreenHeight(context))
                    .crossFade(500)
                    .into(imageView);
        }
    }

    class BannerDefaultHolder implements Holder<Integer> {

        private ImageView imageView;

        @Override
        public View createView(Context context) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.FIT_XY);
            return imageView;
        }

        @Override
        public void UpdateUI(Context context, int position, Integer data) {
            Glide.with(context)
                    .load(data)
                    .override(ScreenUtil.getScreenWidth(context),ScreenUtil.getScreenHeight(context))
                    .into(imageView);
        }
    }

    public boolean isFirstIn(){
        return "true".equals(SharePrefrenceUtil.get(this, "isFirst", "true"));
    }

    private void decideToGo() {
        if (!hasGO) {
            displayWebViewContent();
            hasGO = true;
        }else {
            Logger.i(TAG,"decideToGo already go main"+ XulUtils.timestamp_us());
        }
    }
    private void displayWebViewContent() {
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                bannerLayout.setVisibility(View.GONE);
                rtlWebContent.setVisibility(View.VISIBLE);
                SharePrefrenceUtil.put(MainActivity.this, "isFirst", "false");
                dbProcess.setVisibility(View.VISIBLE);
                loadPage(Constant.URL_Main);
            }
        });
    }
}
